﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace FileRenamer
{
    class FrequentReplacements
    {
        class Replacement
        {
            public String OldValue;
            public String NewValue;
        }
        
        private IList<Replacement> Replacements = new List<Replacement>();

        public void Load()
        {
            if (!File.Exists("FrequentReplacements.txt"))
                return;
            using (StreamReader sr = new StreamReader("FrequentReplacements.txt", Encoding.Unicode))
            {
                while (!sr.EndOfStream)
                {
                    string line= sr.ReadLine();
                    string []parts= line.Split("\t".ToCharArray());
                    if (parts.Length != 2)
                    {
                        Trace.WriteLine("La linea no tiene el formato esperado: " + line);
                    }
                    else
                    {
                       Add(parts[0], parts[1]);
                    }
                }


            }

        }
        public void Save()
        {
            using (StreamWriter sw = new StreamWriter("FrequentReplacements.txt", false, Encoding.Unicode))
            {
                foreach (Replacement replacement in Replacements)
                {
                    string line = string.Format("{0}\t{1}", replacement.OldValue, replacement.NewValue);
                    sw.WriteLine(line);
                }

            }
        }
        public void Add(String oldValue, String newValue)
        {
            Replacement replacement = new Replacement();
            replacement.OldValue = oldValue;
            replacement.NewValue = newValue;
            Replacements.Add(replacement);
        }
        public String Apply(String input)
        {
            string convertedText= input;
            foreach (Replacement replacement in Replacements)
            {
                convertedText = convertedText.Replace(replacement.OldValue, replacement.NewValue);
            }
            return convertedText;
        }


    }
}
